import { service } from './service'

import { config } from './config'

const { default_headers } = config

const request = (option: any) => {
  const { url, method, params, data, headersType, responseType, ...config } = option
  return service({
    url: url,
    method,
    params,
    data,
    ...config,
    responseType: responseType,
    headers: {
      'Content-Type': headersType || default_headers
    }
  })
}
export default {
  get: async <T = any>(option: any) => {
    const res = await request({ method: 'GET', ...option })
    return res as unknown as T
  },
  post: async <T = any>(option: any) => {
    const res = await request({ method: 'POST', ...option })
    return res as unknown as T
  },
  postOriginal: async (option: any) => {
    const res = await request({ method: 'POST', ...option })
    return res
  },
  delete: async <T = any>(option: any) => {
    const res = await request({ method: 'DELETE', ...option })
    return res as unknown as T
  },
  put: async <T = any>(option: any) => {
    const res = await request({ method: 'PUT', ...option })
    return res as unknown as T
  },
  download: async <T = any>(option: any) => {
    const res = await request({ method: 'GET', responseType: 'blob', ...option })
    return attachmentAdpator(res) as unknown as Promise<T>
    // return res.data as unknown as Promise<T>
  },
  upload: async <T = any>(option: any) => {
    option.headersType = 'multipart/form-data'
    const res = await request({ method: 'POST', ...option })
    return res as unknown as Promise<T>
  }
}

const attachmentAdpator = (response: any)=>{
  if (response && response.headers && response.headers['content-disposition']) {
    const disposition = response.headers['content-disposition'];
    let filename = '';

    if (disposition && disposition.indexOf('attachment') !== -1) {
      // disposition 有可能是 attachment; filename="??.xlsx"; filename*=UTF-8''%E4%B8%AD%E6%96%87.xlsx
      // 这种情况下最后一个才是正确的文件名
      const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/i;

      const matches = disposition.match(filenameRegex);
      if (matches && matches.length) {
        filename = matches[1].replace(`UTF-8''`, '').replace(/['"]/g, '');
      }

      // 很可能是中文被 url-encode 了
      if (filename && filename.replace(/[^%]/g, '').length > 2) {
        filename = decodeURIComponent(filename);
        // 有些后端用错了，导致空格转义成了 +，这里转回来
        filename = filename.replace(/\+/g, ' ');
      }
    }

    const type = response.headers?.['content-type'];
    const blob =
      response.data.toString() === '[object Blob]'
        ? response.data
        : new Blob([response.data], {type: type});
    if (typeof (window.navigator as any).msSaveBlob !== 'undefined') {
      // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
      (window.navigator as any).msSaveBlob(blob, filename);
    } else {
      const URL = window.URL || (window as any).webkitURL;
      const downloadUrl = URL.createObjectURL(blob);
      if (filename) {
        // use HTML5 a[download] attribute to specify filename
        const a = document.createElement('a');
        // safari doesn't support this yet
        if (typeof a.download === 'undefined') {
          (window as any).location = downloadUrl;
        } else {
          a.href = downloadUrl;
          a.download = filename;
          document.body.appendChild(a);
          a.click();
        }
      } else {
        (window as any).location = downloadUrl;
      }
      setTimeout(function () {
        URL.revokeObjectURL(downloadUrl);
      }, 100); // cleanup
    }

    return {
      ...response,
      data: {
        status: 0,
        // msg: __('Embed.downloading')
      }
    };
  } else if (response.data && response.data.toString() === '[object Blob]') {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.addEventListener('loadend', e => {
        const text = reader.result as string;

        try {
          resolve({
            ...response,
            data: {
              ...JSON.parse(text)
            }
          });
        } catch (e) {
          reject(e);
        }
      });

      reader.readAsText(response.data);
    });
  }

  return response.data;

}

